<template>
  <div class="game-wp" >
      <div class="top-bar">
          <div class="user">
              <span class="label">玩家</span>
              <span class='value'>{{userName}}</span>
          </div>
          <div class="center-view">
              <span class="label">总用时</span>
              <span class="value">{{totalTime}}</span>
          </div>
          <div class="score">
              <span class="label">得分</span>
              <span class="value">{{score}}</span>
          </div>
      </div>

      <div class="game-win" style='width: 100%;height: calc(100vh - 100px);display: flex;'>
        <div class="dao-1">
            <div class="dao-2">
                <div class="thief-box" :style='calcThief'></div>
                <div class="police-box" :style='calcPolice'></div>
            </div>
        </div>
          
      </div>
      <div class="bottom-bar">
          <div class="tm-box" >
            <div class="timu-str">{{tm}}</div>
            <div class="fuhao">=</div>
            <div class="res">
                <el-input type="text" class="res-input" v-model="res"/>
            </div>
          </div>
          <div class="handle" @click='onSubmit'>提交</div>
      </div>
      <canvas id="canvas" :style='`z-index: ${this.zIndex}`'></canvas>
  </div>
</template>

<script>
import {numFuctory } from '@/util/common'
export default {
    data: () => ({
        userName: '郭明谦',
        score: 0,
        tm: '',
        res: '',
        rightRes: '',
        totalTime: '',
        count: 0,
        zIndex: -1,
        thiefSpeed: 1,
        policeSpeed: 1,
        timeLong: null,
        thiefPoi: {
            top: -60,
            left: -60,
        },
        policePoi: {
            top: 340,
            left: 1070,
        },
        policePoiNew: null,
        thiefPoiNew: null,
        calcThief:{top: '340px', left: '1070px', transform: 'rotateY(180deg)'},// {top: '-60px', left: '-60px'},
        calcPolice: {top: '-60px', left: '-60px' },//{top: '340px', left: '1070px'},
        hasAdd: true,
        addType: 1,

    }),


    mounted() {
        this.createSub()        
    },

    methods: {
        createSub() {
            let flagInd = numFuctory(4)
            let res = this[`made${flagInd}`]()
            this.tm = res.str
            this.rightRes = res.right
        },

        made0(num1 = numFuctory(100), num2 = numFuctory(100)) {
            return {str: `${num1} + ${num2}`, right: num1 + num2}
        },

        made1(num1 = numFuctory(100), num2 = numFuctory(100)) {
            let max = Math.max(num1, num2)
            let min = Math.min(num1, num2)
            return {str: `${max} - ${min}`, right: max - min}
        },

        made2() {
            let num1 = numFuctory(100), num2 = numFuctory(10)
            return {str: `${num1} × ${num2}`, right: num1 * num2}
        },

        made3() {
            let num2 = numFuctory(10, 1)
            let right = numFuctory(10, 1)
            let num1 = num2 * right
            return {str: `${num1} ÷ ${num2}`, right}
        },

        onSubmit() {            
            !this.runAni && this.beginAni()
            this.timeLong = Date.now() + 5000
            this.hasAdd = false
            if(this.res == this.rightRes) {
                this.score += 2
                this.addType = 1
            }else {
                this.addType = 2
            }
            this.res = ''
            this.count ++
            if(this.count == 50) {
                this.score > 60 && this.qingzhu();
                return 
            }
            this.createSub()
        },

        async qingzhu() {
            this.runAni = false
            this.thiefPoi = { top: -60, left: -60, }
            this.policePoi = { top: 340, left: 1070,}
            this.calcThief = {top: '340px', left: '1070px', transform: 'rotateY(180deg)'}
            this.calcPolice = {top: '-60px', left: '-60px' }
            for(let i = 100; i > 0; i++){
                this.yanhua()
                await new Promise(r => setTimeout( r, 4000))
            }            
        },
        yanhua(){
             // 创建Canvas元素
            this.zIndex = 99
            let canvas = document.getElementById('canvas');
            let ctx = canvas.getContext('2d');
    // 存储烟花的数组
            let fireworks = [];

            // 设置Canvas样式和位置
            function setCanvasStyle() {
                canvas.style.position = 'fixed';
                canvas.style.top = '0';
                canvas.style.left = '0';
                canvas.style.pointerEvents = 'none'; // 不影响原网页的鼠标事件
            }

            // 设置Canvas大小
            function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
            }

            // 初始化Canvas样式和大小
            setCanvasStyle();
            resizeCanvas();

            // 窗口大小改变时重新设置Canvas大小
            window.addEventListener('resize', function() {
                resizeCanvas();
            });

            let w = window.innerWidth
            let h = window.innerHeight
            
                let x = numFuctory(w, w/3)
                let y = numFuctory(h, h/3)
                createFirework(x, y);                
                animate();

            // 鼠标点击事件监听器
            // document.addEventListener('click', function(event) {
            //     createFirework(event.clientX, event.clientY);
            // });

            // 创建烟花函数
            function createFirework(x, y) {
                fireworks.push(new Firework(x, y));
            }

            // 烟花对象构造函数
            function Firework(x, y) {
                this.x = x;
                this.y = y;
                this.particles = [];

                // 创建烟花粒子
                for (let i = 0; i < 30; i++) {
                    this.particles.push(new Particle(this.x, this.y));
                }

                // 更新和绘制烟花粒子
                this.update = function() {
                    for (let i = 0; i < this.particles.length; i++) {
                        this.particles[i].update();
                        this.particles[i].draw();
                    }
                }
            }

            // 烟花粒子对象构造函数
            function Particle(x, y) {
                this.x = x + (Math.random() - 0.5) * 10; // 将烟花爆炸范围控制在鼠标周围
                this.y = y + (Math.random() - 0.5) * 10; // 将烟花爆炸范围控制在鼠标周围
                this.radius = Math.random() * 2 + 1;
                this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
                this.velocity = {
                    x: Math.random() * 6 - 3,
                    y: Math.random() * 6 - 3
                };
                this.alpha = 1;

                // 更新粒子位置和透明度
                this.update = function() {
                    this.x += this.velocity.x;
                    this.y += this.velocity.y;
                    this.alpha -= 0.01;
                }

                // 绘制粒子
                this.draw = function() {
                    ctx.save();
                    ctx.globalAlpha = this.alpha;
                    ctx.fillStyle = this.color;
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.restore();
                }
            }

            // 动画循环
            function animate() {
                requestAnimationFrame(animate);
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                // 更新和绘制烟花
                for (let i = 0; i < fireworks.length; i++) {
                    fireworks[i].update();
                }

                // 清除已消失的烟花
                fireworks = fireworks.filter(function(firework) {
                    return firework.particles[0].alpha > 0;
                });
            }
            
        },

        async beginAni() {
            this.runAni = true
            while(this.runAni) {
                if(!this.hasAdd && this.timeLong > Date.now()) {
                    this.thiefSpeed = this.addType == 1 ? 1 : 2
                    this.policeSpeed = this.addType == 1 ? 3 : 1
                }else {
                    this.hasAdd = true
                    this.thiefSpeed = this.policeSpeed = 1
                }
                this.thiefPoiNew = this.createPoi(this.thiefPoi, this.thiefSpeed)
                this.policePoiNew = this.createPoi(this.policePoi, this.policeSpeed)
                this.calcThief = this.creatCalc(this.thiefPoiNew)
                this.calcPolice = this.creatCalc(this.policePoiNew)
                if(this.panduan()) this.qingzhu()
                this.thiefPoi = this.thiefPoiNew
                this.policePoi = this.policePoiNew
                await new Promise( r => setTimeout(r, 50))
            }
        },

        panduan() {
            let {top: py, left: px} = this.policePoi
            let {top: pyn, left: pxn} = this.policePoiNew
            let {top: ty, left: tx} = this.thiefPoi
            let {top: tyn, left: txn} = this.thiefPoiNew
            if(py == pyn && ty == tyn && py == ty) {
                if(px < pxn && px < tx && pxn >= txn){
                    return true
                }
                if(px > pxn && px > tx && pxn <= txn){
                    return true
                }
            }
            if(px == pxn && tx == txn && tx == px) {
                if(py > pyn && py > ty && pyn <= tyn){
                    return true
                }
                if(py < pyn && py < ty && pyn >= tyn){
                    return true
                }
            }
        },

        createPoi(poi, speed){
            let {top, left, transform} = poi
            let n;
            if(top == -60 && left > -60){
                n = left - speed
                if(n <= -60) {
                    transform = transform ? undefined : 'rotateY(180deg)'
                    left = -60
                }else {left = n}
            }else if(left == -60 && top < 340){
                n = top + speed
                top = n >= 340 ? 340 : n
            }else if (top == 340 && left < 1070){
                n = left + speed
                if(n >= 1070) {
                    transform = transform ? undefined : 'rotateY(180deg)'
                    left = 1070
                }else {
                    left = n
                }
            }else if(left == 1070 && top > -60){
                n = top - speed
                top = n < -60 ? -60 : n
            }
            return {top,left,transform}
        },

        creatCalc(poi) {
            console.log(poi, 'poi');
            return {
                top: poi.top + 'px',
                left: poi.left + 'px',
                transform: poi.transform
            }
        }


    }

}
</script>

<style lang="scss" scoped>
.game-wp{
    width: 100%;
    height: 100%;
    position: relative;
    .top-bar{
        display: flex;
        background: #ffffff55;
        line-height: 30px;
        justify-content: space-between;
        padding: 10px 50px;
        .label{
            margin-right: 20px;
            color: #fef0f0;
        }
        .value{
            color: gold;
        }
    }
    .game-win{
       .dao-1{
           width: 1200px;
           height: 500px;
           border-radius: 20px;
           border: 150px solid #F56C6C;
           margin: auto;
           .dao-2{
               position: relative;
               top: -100px;
               left: -100px;
               width: 1100px;
               height: 400px;
               border-radius: 20px;
               border: 20px solid #fff;
               .police-box,.thief-box{
                   width: 60px;
                   height: 60px;
                   position: absolute;
               }
               .police-box{
                   background: url(@/assets/image/police.gif);
                   background-size: 100% 100%;
               }
               .thief-box{
                   background: url(@/assets/image/thief.gif);
                   background-size: 100% 100%;                   
               }
           }

       } 
    }
    .bottom-bar{
        position: fixed;
        bottom: 0;
        width: 100vw;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 16px;
        line-height: 20px;
        height: 100px;
        .tm-box{
            display: flex;
            margin-right: 40px;
            line-height: 40px;
            background: #fff;
            padding: 10px 50px;
            .fuhao{margin: auto 20px;}
        }
        .handle{
            box-shadow: 0px 0px 15px 3px yellow inset;
            padding: 20px 40px;
            color: #fff;
            cursor: pointer;
            margin-right: 20px;
            border-radius: 30px;
        }
    }
    #canvas{
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
    }
}
</style>>

</style>